<template>
  <div class="orders-container">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="nav-content">
        <div class="logo">
          <span class="logo-icon">✈️</span>
          <span class="logo-text">旅游平台</span>
        </div>
        <div class="nav-user">
          <!-- 通知中心 -->
          <NotificationCenter />
          
          <el-button @click="router.push('/home')" type="text">
            <el-icon><ArrowLeft /></el-icon>
            返回首页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="content">
      <div class="page-header">
        <h1>我的订单</h1>
        <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
          <el-tab-pane label="全部" name=""></el-tab-pane>
          <el-tab-pane label="待支付" name="pending"></el-tab-pane>
          <el-tab-pane label="已支付" name="paid"></el-tab-pane>
          <el-tab-pane label="已完成" name="completed"></el-tab-pane>
          <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- 订单列表 -->
      <div class="orders-list" v-loading="loading">
        <el-empty v-if="!loading && orders.length === 0" description="暂无订单" />
        
        <div v-for="order in orders" :key="order.id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.order_no }}</span>
              <span class="order-time">{{ formatTime(order.created_at) }}</span>
            </div>
            <el-tag :type="getStatusType(order.status)">
              {{ getStatusText(order.status) }}
            </el-tag>
          </div>

          <div class="order-body">
            <div class="attraction-info">
              <h3>{{ order.attraction_name || '景点名称' }}</h3>
              <div class="order-details">
                <span>数量：{{ order.quantity }}张</span>
                <span>单价：¥{{ order.unit_price }}</span>
              </div>
            </div>
            <div class="order-amount">
              <span class="amount-label">总金额</span>
              <span class="amount-value">¥{{ order.total_amount }}</span>
            </div>
          </div>

          <div class="order-footer">
            <div class="contact-info" v-if="order.contact_name || order.contact_phone">
              <span v-if="order.contact_name">联系人：{{ order.contact_name }}</span>
              <span v-if="order.contact_phone">电话：{{ order.contact_phone }}</span>
            </div>
            <div class="order-actions">
              <el-button @click="viewOrderDetail(order.id)" type="primary" link>
                查看详情
              </el-button>
              <el-button
                v-if="order.status === 'pending'"
                @click="payOrder(order)"
                type="primary"
              >
                立即支付
              </el-button>
              <el-button
                v-if="order.status === 'pending'"
                @click="cancelOrder(order)"
                type="danger"
                link
              >
                取消订单
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { travelAPI } from '../api/index.js'
import wsClient from '../utils/websocket.js'
import NotificationCenter from '../components/NotificationCenter.vue'

const router = useRouter()

const loading = ref(false)
const orders = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const activeStatus = ref('')

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'paid': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待支付',
    'paid': '已支付',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return textMap[status] || status
}

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      page_size: pageSize.value
    }
    if (activeStatus.value) {
      params.status = activeStatus.value
    }
    
    const response = await travelAPI.getOrders(params)
    orders.value = response.orders || []
    total.value = response.total || 0
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 状态切换
const handleStatusChange = () => {
  page.value = 1
  loadOrders()
}

// 分页大小改变
const handleSizeChange = () => {
  loadOrders()
}

// 页码改变
const handlePageChange = () => {
  loadOrders()
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/orders/${orderId}`)
}

// 支付订单
const payOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认支付订单 ${order.order_no}，金额：¥${order.total_amount}？`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    // 使用新的支付接口
    const response = await travelAPI.createPayment({
      order_id: order.id,
      payment_method: 'alipay'
    })
    
    // 如果返回了支付URL，跳转到支付页面
    if (response.payment_url) {
      ElMessage.success('正在跳转到支付页面...')
      // 在新窗口打开支付页面
      window.open(response.payment_url, '_blank')
    } else {
      ElMessage.success('支付创建成功')
    }
    
    // 刷新订单列表
    await loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付失败:', error)
      ElMessage.error(error.response?.data?.detail || '支付失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 取消订单
const cancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认取消订单 ${order.order_no}？`,
      '确认取消',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    await travelAPI.cancelOrder(order.id)
    ElMessage.success('订单已取消')
    await loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error(error.response?.data?.detail || '取消订单失败')
    }
  } finally {
    loading.value = false
  }
}

// WebSocket消息处理
const handleWebSocketMessage = (event) => {
  if (event.type === 'message' && event.data) {
    const notification = event.data
    // 如果是订单相关的通知，刷新订单列表
    if (notification.type === 'order' || notification.type === 'payment') {
      ElMessage({
        message: notification.message || notification.title,
        type: notification.priority === 'urgent' ? 'error' : 'success',
        duration: 3000
      })
      // 延迟刷新，避免与当前操作冲突
      setTimeout(() => {
        loadOrders()
      }, 1000)
    }
  }
}

onMounted(() => {
  loadOrders()
  
  // 连接WebSocket
  const token = localStorage.getItem('token')
  if (token) {
    wsClient.connect(token)
    wsClient.onMessage(handleWebSocketMessage)
  }
})

onUnmounted(() => {
  wsClient.offMessage(handleWebSocketMessage)
})
</script>

<style scoped>
.orders-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.navbar {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.nav-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

.logo-icon {
  font-size: 24px;
}

.content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.page-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-no {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.order-time {
  color: #999;
  font-size: 14px;
}

.order-body {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.attraction-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #333;
}

.order-details {
  display: flex;
  gap: 16px;
  color: #666;
  font-size: 14px;
}

.order-amount {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.amount-label {
  color: #999;
  font-size: 14px;
  margin-bottom: 4px;
}

.amount-value {
  font-size: 24px;
  font-weight: 600;
  color: #ff6b6b;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.contact-info {
  display: flex;
  gap: 16px;
  color: #666;
  font-size: 14px;
}

.order-actions {
  display: flex;
  gap: 12px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style>

